//
//  ShowTimeViewController.m
//  iOS 自定义时间轴
//
//  Created by Apple on 16/7/26.
//  Copyright © 2016年 zls. All rights reserved.
//

#import "ShowTimeViewController.h"

@interface ShowTimeViewController ()
{
    NSInteger userId;
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
}
@property(strong,nonatomic) UITableView *listTableview;
@property(strong,nonatomic) NSMutableArray *dataList;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(strong,nonatomic) AFHTTPSessionManager *manager;

@end

@implementation ShowTimeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filtPath];
    if (dic != nil) {
        
        if (![[dic objectForKey:@"username"] isKindOfClass:[NSNull class]] && ![[dic objectForKey:@"password"] isKindOfClass:[NSNull class]]) {
            userId = [[dic objectForKey:@"userid"]integerValue];
        }else{
            //读取保存在中间对象中的数据
            UIApplication *app = [UIApplication sharedApplication];
            
            AppDelegate *delegate = app.delegate;
            userId = delegate.userId;
        }
    }
    [self setData];
    [self.listTableview.mj_header beginRefreshing];
}
- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"故障审批列表";
    self.view.backgroundColor=[UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;

}
//设置UI视图
- (void)initTableView{
    
    self.listTableview=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH,kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    self.listTableview.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.listTableview.delegate=self;
    self.listTableview.dataSource=self;
    //去掉多余的cell
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];
    [self.listTableview setTableFooterView:v];
    [self.view addSubview:self.listTableview];
    
    _listTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self setData];
    }];
}
- (void)endRefresh
{
    [self.listTableview.mj_header endRefreshing];
}



//数据
-(void)setData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //请求超时时间设置
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_GZshengpiUrl parameters:@{userid:[NSString stringWithFormat:@"%ld",userId]} progress:^(NSProgress * _Nonnull uploadProgress) {

        
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       [self endRefresh];
       NSDictionary *dicdate = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
       NSLog(@"%@",dicdate);
       NSDictionary *data = dicdate[@"data"];
       NSArray *arr = data[@"FaultRecdlist"];

       self.dataList=[NSMutableArray arrayWithCapacity:0];
       self.dataSource = [[NSMutableArray alloc]init];
       for (NSInteger i = 0; i<arr.count; ++i) {
           
           NSString *strTime = [NSString stringWithFormat:@"%@",arr[i][@"time"]];
           
               NSString *Month_str = [strTime substringWithRange:NSMakeRange(5, 2)];
               NSString *Day_str = [strTime substringWithRange:NSMakeRange(8, 2)];
           NSString *Time = [NSString stringWithFormat:@"%@/%@",Month_str,Day_str];
           
           NSDictionary *dic=@{@"timeStr":Time,@"titleStr":arr[i][@"name"],@"averageScoreStr":arr[i][@"discrib"],@"state":arr[i][@"state"]};
           TimeModel *model=[[TimeModel alloc]initData:dic];
           [self.dataList addObject:model];
           canshuModel *model1 = [[canshuModel alloc]init];
           model1.Parid = [arr[i][@"id"]integerValue];
           [self.dataSource addObject:model1];
       }
       if (self.dataList.count == 0) {
           _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"暂时没有要审批的事件"];
           _nothing.delegate = self;
           [self.view addSubview:_nothing];
       }else{
           
           [self initTableView];
           [self.listTableview reloadData];
       }
       [MBProgressHUD hideHUDForView:self.view animated:YES];
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       [MBProgressHUD hideHUDForView:self.view animated:YES];
       NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
       NSInteger status = responses.statusCode;
       if (status >= 500) {
           _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
           _ServerFView.delegate = self;
           [self.view addSubview:_ServerFView];
       }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
           _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
           _Fallview.delegate = self;
           [self.view addSubview:_Fallview];
       }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
           _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
           _JoinFalutView.delegate = self;
           [self.view addSubview:_JoinFalutView];
       }else{
           [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
       }
   }];
}
- (void)NothingRefresh:(UIButton *)sender{
    
    [_nothing removeFromSuperview];
    [self setData];
}
- (void)FallLineRefresh:(UIButton *)sender{
    
    [_Fallview removeFromSuperview];
    [self setData];
}
- (void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self setData];
}
- (void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self setData];
}

#pragma mark-----------------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId=@"testTime";
    RightSlidetableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell=[[RightSlidetableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    TimeModel *model=self.dataList[indexPath.row];
    [cell setData:model];
    //self.listTableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//     TimeModel *model=self.dataList[indexPath.row];
//    NSDictionary *fontDic=@{NSFontAttributeName:[UIFont systemFontOfSize:18]};
//    CGSize size1=CGSizeMake(kSCREEN_WIDTH,0);
//    CGSize titleLabelSize=[model.titleStr boundingRectWithSize:size1 options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading   attributes:fontDic context:nil].size;
//    NSLog(@"%f",titleLabelSize.height+40);
    //return titleLabelSize.height+40;
    return 62.0;
   
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    canshuModel *model = _dataSource[indexPath.row];

    GZshenpiVC *vc = [[GZshenpiVC alloc]init];
    vc.Pid = [NSString stringWithFormat:@"%ld",model.Parid];
   // vc.prompt = @"不是编辑状态";
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
}




























































- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
